﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Data;
using FU.Capstones.IMS.Web.Common;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.DataContracts;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.EventArgs;
using FU.Capstones.IMS.Web.Silverlight.Models;
using FU.Capstones.IMS.Web.Silverlight.Popups;
using Microsoft.Practices.Prism.Commands;
using Navigation.Silverlight;

namespace FU.Capstones.IMS.Web.Silverlight.ViewModels
{
    public class ExportProductOrderViewModel : ViewModelBase
    {
        public ExportProductOrderViewModel()
        {
            Model = new ExportProductOrderModel();
            ((ExportProductOrderModel)Model).GetWarehouseCollectionCompleted += DoGetWarehouseCollectionCompleted;
            ((ExportProductOrderModel)Model).InsertOrderCompleted += DoInsertOrderCompleted;
            ((ExportProductOrderModel)Model).GetEmployeeCollectionCompleted += DoGetEmployeeCollectionCompleted;
            ((ExportProductOrderModel)Model).GetContactCollectionCompleted += DoGetContactCollectionCompleted;
            CanAdd = true;
            CanEditOrAdd = true;
        }

        #region ImplementEventCompleted

        void DoInsertOrderCompleted(object sender, SingleFeedbackCompletedEventArgs<int> e)
        {
            if (e.Error != null)
            {
                Message = e.Result.Message;
                MessageVisibility = Visibility.Visible;
                MessageBox.Show("Có lỗi không thể nhập được lô sản phẩm !");
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                    MessageBox.Show("Nhập đơn hàng không thành công");
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    CollectionProduct.Clear();
                    SavedCollectionProduct.Clear();
                    MessageBox.Show("Nhập đơn hàng thành công ");

                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;

        }

        void DoGetWarehouseCollectionCompleted(object sender, CollectionFeedbackCompletedEventArgs<Warehouse> e)
        {
            if (e.Error != null)
            {
                Message = e.Result.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    WarehouseCollection = new ObservableCollection<Warehouse>(e.Result.Data);
                    SelectedWarehouse = WarehouseCollection[0];
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }

        void DoGetContactCollectionCompleted(object sender, CollectionFeedbackCompletedEventArgs<Contact> e)
        {
            if (e.Error != null)
            {
                Message = e.Result.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    ContactCollection = new ObservableCollection<Contact>(e.Result.Data);
                    ProductOrder.Contact = ContactCollection[0];
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }
        void DoGetEmployeeCollectionCompleted(object sender, CollectionFeedbackCompletedEventArgs<Employee> e)
        {
            if (e.Error != null)
            {
                Message = e.Result.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    EmployeeACollection = new ObservableCollection<Employee>(e.Result.Data);
                    EmployeeBCollection = new ObservableCollection<Employee>(e.Result.Data);
                    ProductOrder.EmployeeA = EmployeeACollection[0];
                    ProductOrder.EmployeeB = EmployeeBCollection[0];
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }

        #endregion

        #region Declare radCheck
        private DelegateCommand<object> radCheck;
        public DelegateCommand<object> RadCheck
        {
            get
            {
                if (radCheck == null)
                {
                    radCheck = new DelegateCommand<object>(DoRadCheck);
                }
                return radCheck;
            }
        }
        //Add new command use to and a new material loaf
        private DelegateCommand<object> addNewCommand;
        public DelegateCommand<object> AddNewCommand
        {
            get
            {
                if (addNewCommand == null)
                {
                    addNewCommand = new DelegateCommand<object>(DoAddNewCommand);
                }
                return addNewCommand;
            }
        }

        //Save command use to save collection material order to database
        private DelegateCommand<object> saveCommand;
        public DelegateCommand<object> SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new DelegateCommand<object>(DoSaveCommand);
                }
                return saveCommand;
            }
        }

        //Back command use to turn back list order screeen
        private DelegateCommand<object> cancelCommand;
        public DelegateCommand<object> CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new DelegateCommand<object>(DoBackCommand);
                }
                return cancelCommand;
            }
        }
        //Delete command use delete material from list material
        private DelegateCommand<object> deleteCommand;
        public DelegateCommand<object> DeleteCommand
        {
            get
            {
                if (deleteCommand == null)
                {
                    deleteCommand = new DelegateCommand<object>(DoDeleteCommand);
                }
                return deleteCommand;
            }
        }

        //Reset command use to reset list of material
        private DelegateCommand<object> resetCommand;
        public DelegateCommand<object> ResetCommand
        {
            get
            {
                if (resetCommand == null)
                {
                    resetCommand = new DelegateCommand<object>(DoResetCommand);
                }
                return resetCommand;
            }
        }

        #endregion

        #region Implement command
        private void DoRadCheck(object obj)
        {
            if (CollectionProduct != null)
            {
                CollectionProduct.Clear();
            }
            if (SavedCollectionProduct != null)
            {
                SavedCollectionProduct.Clear();
            }

        }
        private void DoAddNewCommand(object obj)
        {
            if (SelectedWarehouse != null)
            {
                
                    NavigationData sendNavigation = new NavigationData();
                    sendNavigation.Data = this;
                    sendNavigation.NavigationUri = WebConstants.NavigationPages.ExportProductOrder;
                    if (IsImported)
                    {
                        NavigationManager.NavigateTo(WebConstants.NavigationPages.ProductLoafImport, sendNavigation);

                    }
                    if (SelectedWarehouse.WarehouseID != 0)
                    {
                        if (IsExported)
                        {
                            NavigationManager.NavigateTo(WebConstants.NavigationPages.ProductExport, sendNavigation);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Bạn chưa chọn kho");
                    }
                    if (IsExported == false && IsImported == false)
                    {
                        MessageBox.Show("Bạn phải lựa chọn nhập hoặc xuất kho!");
                    }
               
            }

        }
        private void DoSaveCommand(object obj)
        {
            if (ProductOrder.EmployeeA != null && (ProductOrder.EmployeeB != null || ProductOrder.Contact != null) && SelectedWarehouse.WarehouseID != 0)
            {
                if (PagedCollectionProduct.Count != 0)
                {

                    SavedProductOrder = ProductOrder;
                    ProductOrder.WarehouseID = SelectedWarehouse.WarehouseID;
                    SavedCollectionProduct.Clear();
                    //check IsInternal and External to verify Contact and EmployeeB
                    //if IsInternal Contact = null
                    //if IsExternal EmployeeB = null
                    if (IsInternal)
                    {
                        ProductOrder.Contact = null;
                    }
                    if (IsExternal)
                    {
                        ProductOrder.EmployeeB = null;
                    }
                    ////get set ordate from enterdate
                    DateTime? orderDate = DateTime.Now;
                    if (EnterDateTime != null)
                    {
                        string enterDateString = string.Format("{0:yyyy-MM-dd }", EnterDateTime)+string.Format("{0:HH:mm:ss}",DateTime.Now);
                        orderDate = DateTime.Parse(enterDateString);
                    }
                    else
                    {
                        EnterDateTime = DateTime.Now;
                    }

                    if (IsImported)
                    {
                        ProductOrder.OrderCode = GetOrderCode(false, true);
                        ProductOrder.OrderDate = orderDate;
                        ProductOrder.ProductCollection = CollectionProduct;
                        ProductOrder.IsImported = true;
                        //if (ProductOrder == SavedProductOrder)
                        //{
                        //    InsertOrderConfirmationPopUp popup = new InsertOrderConfirmationPopUp();
                        //    popup.Show();
                        //    popup.Closed += (sender, e) =>
                        //    {

                        //        if (popup.DialogResult.HasValue && popup.DialogResult.Value)
                        //        {
                        //            ServiceCallCounter += ((ExportProductOrderModel)Model).InsertOrderAsync(ProductOrder);
                        //        }
                        //    };
                        //}
                        //else
                        //{
                        //    ServiceCallCounter += ((ExportProductOrderModel)Model).InsertOrderAsync(ProductOrder);
                        //}
                        ServiceCallCounter += ((ExportProductOrderModel)Model).InsertOrderAsync(ProductOrder);


                    }
                    if (IsExported)
                    {
                        ProductOrder.OrderCode = GetOrderCode(false, false);
                        ProductOrder.OrderDate = orderDate;
                        ProductOrder.ProductCollection = CollectionProduct;
                        ProductOrder.IsImported = false;
                        //if (ProductOrder == SavedProductOrder)
                        //{
                        //    InsertOrderConfirmationPopUp popup = new InsertOrderConfirmationPopUp();
                        //    popup.Show();
                        //    popup.Closed += (sender, e) =>
                        //    {
                        //        if (popup.DialogResult.HasValue && popup.DialogResult.Value)
                        //        {
                        //            ServiceCallCounter += ((ExportProductOrderModel)Model).InsertOrderAsync(ProductOrder);
                        //        }
                        //    };
                        //}
                        //else
                        //{
                        //    ServiceCallCounter += ((ExportProductOrderModel)Model).InsertOrderAsync(ProductOrder);
                        //}
                        ServiceCallCounter += ((ExportProductOrderModel)Model).InsertOrderAsync(ProductOrder);
                    }
                    if (IsExported == false && IsImported == false)
                    {
                        MessageBox.Show("Bạn phải chọn hoặc là nhập hoặc là xuất kho!");
                    }
                }
                else
                {
                    MessageBox.Show("Bạn chưa chọn nguyên vật liệu nào cả!");
                }

            }
            else
            {
                MessageBox.Show("Bạn chưa điền đủ thông tin");
            }

        }
        private void DoBackCommand(object obj)
        {
            NavigationManager.NavigateTo(WebConstants.NavigationPages.MaterialOrderList);
        }
        private void DoResetCommand(object obj)
        {
            if (CollectionProduct != null)
            {
                CollectionProduct.Clear();
            }
            if (SavedCollectionProduct != null)
            {
                SavedCollectionProduct.Clear();
            }

            ProductOrder.EmployeeA = EmployeeACollection[0];
            ProductOrder.EmployeeB = EmployeeBCollection[0];
            ProductOrder.Contact = ContactCollection[0];
            SelectedWarehouse = WarehouseCollection[0];
        }
        private void DoDeleteCommand(object obj)
        {
            int deletedProductId = (int)obj;
            if (CollectionProduct != null)
            {
                for (int i = 0; i < CollectionProduct.Count; i++)
                {
                    if (CollectionProduct[i].ProductID == deletedProductId)
                    {
                        Product remove = CollectionProduct[i];
                        CollectionProduct.RemoveAt(i);
                        SavedCollectionProduct.Insert(0, remove);

                    }
                }
            }
        }
        #endregion

        #region Save state

        private Warehouse selectedWarehouse;
        public Warehouse SelectedWarehouse
        {
            get { return selectedWarehouse; }
            set
            {
                if (!ReferenceEquals(selectedWarehouse, value))
                {
                    selectedWarehouse = value;
                    RaisePropertyChanged(() => SelectedWarehouse);
                }

            }
        }

        #endregion

        #region Biding to combobox

        private ObservableCollection<Warehouse> warehouseCollection;
        public ObservableCollection<Warehouse> WarehouseCollection
        {
            get { return warehouseCollection; }
            set
            {
                if (!ReferenceEquals(warehouseCollection, value))
                {
                    warehouseCollection = value;
                    RaisePropertyChanged(() => WarehouseCollection);
                }
            }
        }

        private ObservableCollection<Employee> employeeBCollection;
        public ObservableCollection<Employee> EmployeeBCollection
        {
            get { return employeeBCollection; }
            set
            {
                if (!ReferenceEquals(employeeBCollection, value))
                {
                    employeeBCollection = value;
                    RaisePropertyChanged(() => EmployeeBCollection);
                }
            }
        }

        private ObservableCollection<Employee> employeeACollection;
        public ObservableCollection<Employee> EmployeeACollection
        {
            get { return employeeACollection; }
            set
            {
                if (!ReferenceEquals(employeeACollection, value))
                {
                    employeeACollection = value;
                    RaisePropertyChanged(() => EmployeeACollection);
                }
            }
        }

        private ObservableCollection<Contact> contactCollection;
        public ObservableCollection<Contact> ContactCollection
        {
            get { return contactCollection; }
            set
            {
                if (!ReferenceEquals(contactCollection, value))
                {
                    contactCollection = value;
                    RaisePropertyChanged(() => ContactCollection);
                }
            }
        }
        #endregion

        #region Material loaf collection
        private PagedCollectionView productLoafCollection;
        public PagedCollectionView ProductLoafCollection
        {
            get { return productLoafCollection; }
            set
            {
                if (!ReferenceEquals(productLoafCollection, value))
                {
                    productLoafCollection = value;
                    RaisePropertyChanged(() => ProductLoafCollection);
                }
            }
        }
        #endregion

        #region ProductOrder
        private Order productOrder;
        public Order ProductOrder
        {
            get { return productOrder; }
            set
            {
                if (!ReferenceEquals(productOrder, value))
                {
                    productOrder = value;
                    RaisePropertyChanged(() => ProductOrder);
                }
            }
        }

        #endregion
        #region SavedProductOrder
        private Order savedProductOrder;
        public Order SavedProductOrder
        {
            get { return savedProductOrder; }
            set
            {
                if (!ReferenceEquals(savedProductOrder, value))
                {
                    savedProductOrder = value;
                    RaisePropertyChanged(() => SavedProductOrder);
                }
            }
        }

        #endregion

        #region Collection Product

        private ObservableCollection<Product> collectionProduct;
        public ObservableCollection<Product> CollectionProduct
        {
            get { return collectionProduct; }
            set
            {
                if (!ReferenceEquals(collectionProduct, value))
                {
                    collectionProduct = value;
                    RaisePropertyChanged(() => CollectionProduct);
                }
            }
        }
        #endregion

        #region Saved Collection Product
        private ObservableCollection<Product> savedCollectionProduct;
        public ObservableCollection<Product> SavedCollectionProduct
        {
            get { return savedCollectionProduct; }
            set
            {
                if (!ReferenceEquals(savedCollectionProduct, value))
                {
                    savedCollectionProduct = value;
                    RaisePropertyChanged(() => SavedCollectionProduct);
                }
            }
        }

        private PagedCollectionView pagedCollectionProduct;
        public PagedCollectionView PagedCollectionProduct
        {
            get { return pagedCollectionProduct; }
            set
            {
                if (!ReferenceEquals(pagedCollectionProduct, value))
                {
                    pagedCollectionProduct = value;
                    RaisePropertyChanged(() => PagedCollectionProduct);
                }
            }
        }

        #endregion

        #region Implementation of INavigationAware

        public override void OnNavigate(object extraData)
        {

            var nd = (NavigationData)extraData;
            if (nd != null)
            {
                if (nd.NavigationUri.Equals(WebConstants.NavigationPages.ProductLoafImport) || nd.NavigationUri.Equals(WebConstants.NavigationPages.ProductExport))
                {
                    if (nd.Data.GetType().Equals(typeof(ExportProductOrderViewModel)))
                    {
                        this.PagedCollectionProduct = ((ExportProductOrderViewModel)nd.Data).PagedCollectionProduct;
                        this.WarehouseCollection = ((ExportProductOrderViewModel)nd.Data).WarehouseCollection;
                        //biding data to combobox
                        this.EmployeeACollection = ((ExportProductOrderViewModel)nd.Data).EmployeeACollection;
                        this.EmployeeBCollection = ((ExportProductOrderViewModel)nd.Data).EmployeeBCollection;
                        this.ContactCollection = ((ExportProductOrderViewModel)nd.Data).ContactCollection;
                        this.CollectionProduct = ((ExportProductOrderViewModel)nd.Data).CollectionProduct;
                        this.ProductOrder = ((ExportProductOrderViewModel)nd.Data).ProductOrder;
                        this.SelectedWarehouse = ((ExportProductOrderViewModel)nd.Data).SelectedWarehouse;

                        //biding saved state for radiobutton
                        this.IsExported = ((ExportProductOrderViewModel)nd.Data).IsExported;
                        this.IsImported = ((ExportProductOrderViewModel)nd.Data).IsImported;
                        this.IsInternal = ((ExportProductOrderViewModel)nd.Data).IsInternal;
                        this.IsExternal = ((ExportProductOrderViewModel)nd.Data).isExternal;
                        //biding to enter date
                        this.EnterDateTime = ((ExportProductOrderViewModel)nd.Data).EnterDateTime;
                        this.SavedCollectionProduct = ((ExportProductOrderViewModel)nd.Data).SavedCollectionProduct;
                    }
                }
            }
            else
            {
                ServiceCallCounter += ((ExportProductOrderModel)Model).GetWarehouseCollectionAsync(false);
                ServiceCallCounter += ((ExportProductOrderModel)Model).GetEmployeeCollectionAsync(false);
                ServiceCallCounter += ((ExportProductOrderModel)Model).GetContactCollectionAsync(false);
                CollectionProduct = new ObservableCollection<Product>();
                PagedCollectionProduct = new PagedCollectionView(CollectionProduct);
                SavedCollectionProduct = new ObservableCollection<Product>();
                ProductOrder = new Order();
                SelectedWarehouse = new Warehouse();
                IsImported = true;
                IsInternal = true;
            }

        }

        public override void OnLeave()
        {
            //will be implemented in the sub classes
        }

        #endregion

        private DateTime? enterDateTime;
        public DateTime? EnterDateTime
        {
            get { return enterDateTime; }
            set
            {
                enterDateTime = value;
                RaisePropertyChanged(() => EnterDateTime);
            }
        }
        private DateTime? savedDateTime;
        public DateTime? SavedDateTime
        {
            get { return savedDateTime; }
            set
            {
                savedDateTime = value;
                RaisePropertyChanged(() => SavedDateTime);
            }
        }
        private bool isImported;
        public bool IsImported
        {
            get { return isImported; }
            set
            {
                isImported = value;
                RaisePropertyChanged(() => IsImported);

            }
        }
        private bool isExported;
        public bool IsExported
        {
            get { return isExported; }
            set
            {
                isExported = value;
                RaisePropertyChanged(() => IsExported);

            }
        }
        private bool isInternal;
        public bool IsInternal
        {
            get { return isInternal; }
            set
            {
                isInternal = value;
                RaisePropertyChanged(() => IsInternal);

            }
        }
        private bool isExternal;
        public bool IsExternal
        {
            get { return isExternal; }
            set
            {
                isExternal = value;
                RaisePropertyChanged(() => IsExternal);

            }
        }

        #region GetOrderCode
        public string GetOrderCode(bool isMaterial, bool isImport)
        {
            string orderCode = "";
            if (isMaterial)
            {
                if (isImport)
                {
                    orderCode = orderCode + "MI";
                }
                if (!isImport)
                {
                    orderCode = orderCode + "ME";
                }
            }
            if (!isMaterial)
            {
                if (isImport)
                {
                    orderCode = orderCode + "PI";
                }
                if (!isImport)
                {
                    orderCode = orderCode + "PE";
                }
            }
            orderCode = orderCode + string.Format("{0:yyMMddHHmmss}", DateTime.Now);
            return orderCode;
        }

        #endregion

    }
}
